package com.usian.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.UUID;

public class Base64FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(Base64FileUtil.class);

    public static void main(String[] args) {

        try {
            String ret = Base64FileUtil.encodeBase64File("d://java.pdf");
            String str = ret+"11212232434";

            /*String path = "d://1.txt";
            BufferedWriter out = new BufferedWriter(new FileWriter(path));
            out.write(ret);
            out.close();*/

            Base64FileUtil.decoderBase64File(str, "d://ghsTest/挂号费电子票据33333.pdf", "d://ghsTest/");
        } catch (Exception e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } finally {


        }
    }

    /**
     * 将文件转成base64 字符串
     *
     * @param
     * @return *
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath, String catalogue)
            throws Exception {
        File file = new File(catalogue);
        if (file.exists() == false) {
            file.mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    public static void base64StringToPDF(String base64sString) {
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            // 将base64编码的字符串解码成字节数组
            byte[] bytes = new BASE64Decoder().decodeBuffer(base64sString);
            // apache公司的API
            // byte[] bytes = Base64.decodeBase64(base64sString);
            // 创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            // 创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            // 指定输出的文件
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            File file = new File("D:\\" + name + ".pdf");
            // 创建到指定文件的输出流
            fout = new FileOutputStream(file);
            // 为文件输出流对接缓冲输出流对象
            bout = new BufferedOutputStream(fout);

            byte[] buffers = new byte[1024];
            int len = bin.read(buffers);
            while (len != -1) {
                bout.write(buffers, 0, len);
                len = bin.read(buffers);
            }
            // 刷新此输出流并强制写出所有缓冲的输出字节，必须这行代码，否则有可能有问题
            bout.flush();

            System.out.println("===================");
        } catch (IOException e) {
            logger.error("base64StringToPDF error", e);
        } finally {
            try {
                bin.close();
                fout.close();
                bout.close();
                // System.out.println("*****************");
            } catch (IOException e) {
                logger.error("base64StringToPDF error", e);
            }
        }
    }


}
